package com.mingtu.jgspatrol.activity;

import android.content.Intent;
import android.net.Uri;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingActivity;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.ParkPeopleInfoAdapter;
import com.mingtu.jgspatrol.bean.ReserveDetailsBean;
import com.mingtu.jgspatrol.databinding.ActivityParkReserveDetailBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.util.HashMap;
import java.util.List;

public class ParkReserveDetailActivity extends BaseBindingActivity<ActivityParkReserveDetailBinding> {


    private int reservationId;
    private ParkPeopleInfoAdapter parkPeopleInfoAdapter;
    private String phoneNo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_park_reserve_detail;
    }

    @Override
    protected void initView() {
        setModuleTitle("详情");
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getData() {
        reservationId = getIntent().getIntExtra("id", 0);
        getDetails();
        addClickListener(this, binding.tvTel);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_tel:
                if (!StringUtils.isEmpty(phoneNo)) callPhone(phoneNo);
                break;
        }
    }

    private void getDetails() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("reservationId", reservationId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_RESERVATION_DETAIL + "/" + reservationId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            ReserveDetailsBean reserveDetailsBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                reserveDetailsBean = new ReserveDetailsBean();
                                reserveDetailsBean = gson.fromJson(result, ReserveDetailsBean.class);
                                ReserveDetailsBean.DataBean dataBean = reserveDetailsBean.getData();
                                String date = dataBean.getReservationDate(); //预约日期
                                String parkName = dataBean.getParkName(); //预约地点
                                String reason = dataBean.getReason();   //事由
                                int vehicle = dataBean.getVehicle(); //交通方式 1：步行 2：自驾
                                String plateNo = dataBean.getPlateNo(); //车牌号
                                String owner = dataBean.getOwner(); //预约人
                                phoneNo = dataBean.getPhoneNo();              //预约人电话
                                String createTime = dataBean.getCreateTime(); //创建时间
                                String checkTime = dataBean.getCheckTime(); //审核时间
                                String memo = dataBean.getMemo(); //原因
                                int status = dataBean.getStatus(); //状态 0:审核中  1：已通过
                                List<ReserveDetailsBean.DataBean.PersonListBean> personList = dataBean.getPersonList(); //随行人员信息


                                String traffic = vehicle == 1 ? "步行" : "自驾";
                                try {
                                    binding.tvDate.setText(MyUtills.convertDateFormat(date));
                                    binding.tvAddress.setText(parkName);
                                    binding.tvReason.setText(reason);
                                    if (vehicle == 2) {
                                        binding.tvCarNumber.setText(plateNo);
                                        binding.layoutCarNumber.setVisibility(View.VISIBLE);
                                    } else {
                                        binding.layoutCarNumber.setVisibility(View.GONE);
                                    }
                                    binding.tvName.setText(owner);
                                    binding.tvTel.setText(phoneNo);
                                    binding.tvTraffic.setText(traffic);
                                    binding.tvCreateTime.setText(MyUtills.convertDateFormat(createTime));
                                    binding.tvAuditTime.setText(MyUtills.convertDateFormat(checkTime));
                                    binding.tvMemo.setText(memo);
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }

                                if (status > 1) {
                                    binding.tvStatus.setText("不通过");
                                    binding.tvStatus.setTextColor(getResources().getColor(R.color.text_color_ff6));
                                    binding.tvStatus.setBackgroundResource(R.drawable.shape_bg_audit_status2);
                                    binding.layoutMemo.setVisibility(View.VISIBLE);
                                    binding.tvMemo.setText(memo);
                                } else {
                                    binding.tvStatus.setText("通过");
                                    binding.tvStatus.setTextColor(getResources().getColor(R.color.text_color_3d7));
                                    binding.tvStatus.setBackgroundResource(R.drawable.shape_bg_audit_status1);
                                    binding.layoutMemo.setVisibility(View.GONE);
                                }

                                if (personList != null && personList.size() > 0) {
                                    LinearLayoutManager manager = new LinearLayoutManager(context);
                                    binding.recycler.setLayoutManager(manager);
                                    binding.recycler.addItemDecoration(new BottomSpaceItemDecoration(SizeUtils.dp2px(10)));
                                    binding.recycler.addItemDecoration(new TopSpaceItemDecoration(SizeUtils.dp2px(10)));

                                    parkPeopleInfoAdapter = new ParkPeopleInfoAdapter();
                                    binding.recycler.setAdapter(parkPeopleInfoAdapter);
                                    parkPeopleInfoAdapter.addData(personList);
                                    parkPeopleInfoAdapter.setOnItemChildClickListener(new onItemChildClickListener());
                                    binding.layoutPeopleInfo.setVisibility(View.VISIBLE);
                                } else {
                                    binding.layoutPeopleInfo.setVisibility(View.GONE);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });

    }

    private class onItemChildClickListener implements BaseQuickAdapter.OnItemChildClickListener {

        @Override
        public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
            switch (view.getId()) {
                case R.id.tv_phone:
                    ReserveDetailsBean.DataBean.PersonListBean listBean = parkPeopleInfoAdapter.getData().get(i);
                    String phone = listBean.getPersonPhone();
                    callPhone(phone);
                    break;
            }
        }
    }

    private void callPhone(String phone) {
        XXPermissions.with(ParkReserveDetailActivity.this)
                .permission(Permission.CALL_PHONE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.CALL_PHONE)) {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            Uri data = Uri.parse("tel:" + phone);
                            intent.setData(data);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            ToastUtils.showLong("请手动授予拨打电话权限");
                            XXPermissions.startPermissionActivity(ParkReserveDetailActivity.this, permissions);
                        } else {

                        }

                    }
                });

    }

}